<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools show-before>
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="danger" @click="exportData(false)">简单表头导出</el-button>
          <el-button size="small" type="info" @click="exportData(true)">复杂表头导出</el-button>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </pagetools>

      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column align="center" label="头像">
            <template v-slot="{row}">
              <img
                ref="myCanvas"
                v-imagerror="require('@/./assets/common/head.jpg')"
                :src="row.staffPhoto"
                style=" width: 80px; height: 80px; border-radius:50%"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>

          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" align="center" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间">
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate("yyyy/MM/dd") }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="260">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" :disabled="!checkPermission('del-user')" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height:80px">
          <el-pagination :total="page.total" :page-size="page.size" :current-page="page.page" layout="prev,pager,next" @current-change="changePage" />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" />
      <!-- 放置角色分配组件 -->
      <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
    <el-dialog
      title="二维码"
      :visible.sync="showCodeDialog"
    >
      <el-row
        type="flex"
        justify="center"
      >
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import AddEmployee from './components/add-employee.vue'
import formatOfEmployment from '@/api/constant/employees'
import assignRole from './components/assign-role.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
export default {
  components: {
    AddEmployee,
    assignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      userId: '',
      showRoleDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    changePage(newpage) {
      this.page.page = newpage
      this.getEmployeeList()
    },
    // 枚举
    formatEmployment(row, column, cellValue, index) {
      const obj = formatOfEmployment.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗?')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (e) {
        console.log(e)
      }
    },
    // 导出excel数据
    exportData(isComplex) {
      if (isComplex) {
        console.log(isComplex)
      }
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // 获取所有的数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)
        // 复杂表头
        const multiHeader = isComplex ? [['姓名', '主要信息', '', '', '', '', '部门']] : []
        const merges = isComplex ? ['A1:A2', 'B1:F1', 'G1:G2'] : []
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          multiHeader, // 复杂表头
          filename: '员工信息表',
          merges, // 合并选项
          autoWidth: true,
          bookType: 'xlsx'

        })
      })
    },
    // 该方法负责将数组转化成二维数组
    formatJson(headers, rows) {
    // 首先遍历数组
    // 每一个对象
      return rows.map(item => {
        // 数组  属性值
        return Object.values(headers).map(value => {
          // 需要针对几个字段处理- 聘用形式
          if (value === 'formOfEmployment') {
            const obj = formatOfEmployment.hireType.find(i => (i.id + '') === item[value] + '')
            return obj ? obj.value : '未知'
          } else if (value === 'timeOfEntry' || value === 'correctionTime') {
            return formatDate(item[value])
          }

          // 对象属性名对应的属性值数组
          return item[value ]
        })
      })
    },
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)// 将地址转化成二维码
        })
      } else {
        this.$message.warning('您的头像未上传')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }
  }

}

</script>

<style>

</style>
